<?php
// +----------------------------------------------------------------------
// | @filename ApiResponse.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-10-27 15:10:08
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------

namespace Addons\Backend\Http;

use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use Response;

trait ApiResponse
{
    /**
     * 响应数据数据
     * @param $message
     * @param array $data
     * @param $code
     * @param $statusCode
     * @return mixed
     */
    public function response($message, array $data, $code, $statusCode, $header)
    {
        $data = [
            'code' => $code,
            'message' => $message,
            'data' => $data
        ];

        return Response::json($data, $statusCode, $header);
    }

    /**
     * 返回失败
     * @param $message
     * @param int $code
     * @param int $statusCode
     * @param array $header
     * @return mixed
     */
    public function failed($message, $code = 1, $statusCode = FoundationResponse::HTTP_OK, $header = [])
    {
        return $this->response($message, [], $code, $statusCode, $header);
    }

    /**
     * 返回成功
     * @param $data
     * @param string $message
     * @param int $statusCode
     * @param array $header
     * @return mixed
     */
    public function success($data, $message = "success", $statusCode = FoundationResponse::HTTP_OK, $header = [])
    {
        return $this->response($message, $data, 0, $statusCode, $header);
    }

    /**
     * 根据code自动返回
     * @param $res
     * @return mixed
     */
    public function respond($res)
    {
        return $res['code'] ? $this->failed($res['message'], $res['code']) : $this->success($res['data'], $res['message']);
    }
}
